"""
FastAPI 应用的入口文件
"""
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from .config import settings

# 导入路由
from .routers import auth, banners, news, services, company, upload, announcements, messages

# 创建 FastAPI 应用实例
app = FastAPI(
    title="环境工程咨询 API",
    description="环境工程咨询公司管理系统后端API",
    version="1.0.0",
    docs_url="/docs",  # Swagger UI 文档地址
    redoc_url="/redoc"  # ReDoc 文档地址
)

# 配置 CORS（跨域资源共享）
# 根据环境变量动态配置允许的源
allowed_origins = [
    "http://localhost:3000",  # 前端开发地址
    "http://localhost:5173",  # Vite 开发服务器地址
    "http://127.0.0.1:3000",  # 备用地址
    "http://127.0.0.1:5173",  # 备用地址
]

# 添加生产环境的前端URL
frontend_url = os.getenv("FRONTEND_URL")
if frontend_url:
    allowed_origins.append(frontend_url)
    # 同时添加不带协议的版本
    if frontend_url.startswith("http://"):
        allowed_origins.append(frontend_url.replace("http://", "https://"))
    elif frontend_url.startswith("https://"):
        allowed_origins.append(frontend_url.replace("https://", "http://"))

# 在开发环境或调试模式下允许所有源
# 生产环境临时允许所有源来解决跨域问题
if settings.debug or os.getenv("DEBUG", "false").lower() == "true" or True:
    allowed_origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
    allow_headers=["*"],
)

# 创建上传目录
os.makedirs("uploads/images", exist_ok=True)
os.makedirs("uploads/documents", exist_ok=True)
os.makedirs("images", exist_ok=True)

# 配置静态文件服务
# 这样可以通过 /uploads/... 访问上传的文件
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
# 配置images静态文件服务
app.mount("/images", StaticFiles(directory="images"), name="images")

# 注册路由
# 这样做可以保持main.py文件简洁，将具体的API逻辑分散到不同的路由文件中
app.include_router(auth.router)
app.include_router(banners.router)
app.include_router(news.router)
app.include_router(announcements.router)
app.include_router(services.router)
app.include_router(company.router)
app.include_router(messages.router)
app.include_router(upload.router)

@app.get("/")
async def root():
    """根路径测试接口"""
    return {"message": "环境工程咨询 API 正在运行"}

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy"}